package com.hulk.dryad.manage.framework.websocket.server.user;

import cn.hutool.core.util.StrUtil;
import com.hulk.dryad.manage.framework.websocket.common.principal.WsPrincipal;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import java.util.List;

/**
 * websocket 在线用户管理
 *
 * @author hulk
 */
@Slf4j
@RequiredArgsConstructor
public class WsUserManageImpl implements IWsUserManage {
	private final IWsUserStore wsUserStore;

	@Override
	public List<String> getUserList(String tenant) {
		return wsUserStore.listAll(tenant);
	}

	@Override
	public boolean isOnline(String userInfo) {
		return wsUserStore.has(userInfo);
	}

	@EventListener
	public void onSocketConnected(SessionConnectedEvent event) {
		StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
		WsPrincipal principal = (WsPrincipal)sha.getUser();
        String userInfo = principal.getTenant().concat(StrUtil.COLON).concat(principal.getName());
		wsUserStore.put(userInfo);
		log.info("WebSocket SessionId: {} Principal: {}", sha.getSessionId(), userInfo);
	}

	@EventListener
	public void onSocketDisconnected(SessionDisconnectEvent event) {
		StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
		WsPrincipal principal = (WsPrincipal)sha.getUser();
		String userInfo = principal.getTenant().concat(StrUtil.COLON).concat(principal.getName());
		wsUserStore.remove(userInfo);
		log.info("WebSocket SessionId: {} Principal: {}", sha.getSessionId(), userInfo);
	}

}
